package cn.kgc.springcloud.controller;

import cn.hutool.core.util.IdUtil;
import cn.kgc.springcloud.entity.Clazz;
import cn.kgc.springcloud.service.ClazzService;
import cn.kgc.springcloud.vo.ClazzVO;
import org.springframework.util.StringUtils;
import org.springframework.web.bind.annotation.*;
import org.springframework.web.multipart.MultipartFile;

import javax.annotation.Resource;
import java.io.File;
import java.io.IOException;
import java.util.List;
import java.util.UUID;

/**
 * @author 课工场
 * @date 2023/10/19
 * @description
 */
@RestController
@RequestMapping("clazz")
public class ClazzController {

    @Resource
    private ClazzService clazzService;

    @GetMapping
    public List<ClazzVO>  getList(){

       return clazzService.getClazzVOList();

    }


    @DeleteMapping("{id}")
    public Boolean deleteClazz(@PathVariable("id") Integer id){
        return clazzService.removeById(id);
    }


    @PostMapping
    public  Clazz  addClazz(MultipartFile file,String name,Integer tagId) throws IOException {

        // 文件上传
        String originalFilename = file.getOriginalFilename();
        String filenameExtension = StringUtils.getFilenameExtension(originalFilename);
        //生成的是不带-的字符串，类似于：b17f24ff026d40949c85a24f4f375d42
        String simpleUUID = IdUtil.simpleUUID();
        String lastName = simpleUUID+"."+filenameExtension;


        File f = new File("D://upload/" + lastName);

        file.transferTo(f);

        Clazz clazz = new Clazz();
        clazz.setName(name);
        clazz.setTagid(tagId);
        clazz.setPath(lastName);

        clazzService.save(clazz);

        return clazz;

    }


    @GetMapping("{id}")
    public Clazz getById(@PathVariable("id") Integer id){

       return clazzService.getById(id);
    }
}
